package com.situ.mall.controller.back.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.situ.mall.entity.User;



public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String servletPath = request.getServletPath();
		System.out.println("servletPath : " + servletPath);
		
		int lastIndex = servletPath.lastIndexOf(".");
		String extension = "";
		if (lastIndex != -1) {
			extension = servletPath.substring(lastIndex); // .js   .css  .png
		}
		
		// 对特殊的请求不需要登录验证
		if ("/user_login.jsp".equals(servletPath)
				||"/user/getUserLoginPage.action".equals(servletPath)
				|| "/user/login.action".equals(servletPath)
				|| ".js".equals(extension)
				|| ".css".equals(extension)
				|| ".png".equals(extension)) {
			return true;
		} else {// 需要验证
			HttpSession session = request.getSession();
			User user = (User)session.getAttribute("user");
			System.out.println(user);
			// user是null，没有登录情况下，需要重定向到登录界面，但是访问user_login.jsp
			// 也会被拦截，也需要登录。问题就是：要去登录界面但是到登录界面要求你必须是登录状态。
			// 解决方法就是：给一些特殊的请求不进行登录验证，例如：user_login.jsp、/loginServlet
			if (user == null) {
				response.sendRedirect(request.getContextPath() + "/user/getUserLoginPage.action");
				return false;
			}
			  
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
